var app = getApp();
var is_pay = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    getPoster: true,
    editState: false,
      defaultTxt: "在此向你送上一份独一无二的问候。祝愿你和家人平安喜乐，幸福安康，勇闯2019，一起向幸福生活往前冲！",
      inputValue: '在此向你送上一份独一无二的问候。祝愿你和家人平安喜乐，幸福安康，勇闯2019，一起向幸福生活往前冲！',
    perImgUrl: '',
    mainImgWidth: 0,
    mainImgHeight: 0,
    p_width: '', // 页面宽度
    p_height: '', // 页面高度
    filePath: '',
    isGetImage: false,
    hide_canvas: true, //绘图层显示控制变量
    cardId: '',
    noQrCode : false,
    downLoadStatus : false
  },

  // 启动编辑
  editText() {
    this.setData({
      editState: true
    })
  },
  // input事件
  bindTextInput(event) {
    this.setData({
      inputValue: event.detail.value
    });
    console.log(this.data.inputValue);
  },
  // 编辑文字 确定
  editSubmit() {
    var _self = this;
    _self.setData({
      defaultTxt: _self.data.inputValue,
      editState: false
    })
  },
  // 取消编辑文字
  cancelEdit() {
    var _self = this;
    _self.setData({
      defaultTxt: _self.data.defaultTxt,
      inputValue: _self.data.inputValue,
      editState: false
    })
  },
  //去掉二维码
  editCode(e) {
    console.log(e.currentTarget.dataset)
    wx.navigateTo({
      url: '/pages/index/pay?cardId=' + e.currentTarget.dataset.cardId
    });
  },
  makePost() {
    wx.showLoading({
      title: '请稍候...',
    })
    var _self = this;
    var timer = null;
    timer = setInterval(function () {
      if (_self.data.downLoadStatus) {
        wx.hideLoading();
        _self.makePostDo();
        clearInterval(timer);
      } else {
      }
    }, 500);
  },
  makePostDo() {
    this.setData({
      getPoster: false,
    });
    var self = this;
    var p_width = self.data.p_width;
    var p_height = self.data.p_height;
    const ctx = wx.createCanvasContext('textCav');
    ctx.clearRect(0, 0, p_width, p_height);
    // ctx.drawImage('./j-bg.png', 0, 0, p_width, p_height)
    ctx.drawImage(self.data.picurl, 0, 0, p_width, p_height)
    ctx.drawImage('./j-txt.png', p_width *233.5 / 750 , p_height * 410 / 1334, p_width * 283 / 750, p_height * 92 / 1334)

    ctx.setFontSize(15)
    ctx.setTextAlign('center')
    ctx.setFillStyle('#ffdca7')
    if (Math.floor(self.data.inputValue.length / 16) == 1) {
      ctx.fillText(self.data.inputValue.substring(0, 16), p_width * 375 / 750, p_height * 630 / 1334, p_width * 450 / 750)
      ctx.fillText(self.data.inputValue.substring(16), p_width * 375 / 750, p_height * 680 / 1334, p_width * 450 / 750)
    } else if (Math.floor(self.data.inputValue.length / 20) == 2) {
      ctx.fillText(self.data.inputValue.substring(0, 16), p_width * 375 / 750, p_height * 630 / 1334, p_width * 450 / 750)
      ctx.fillText(self.data.inputValue.substring(16, 32), p_width * 375 / 750, p_height * 680 / 1334, p_width * 450 / 750)
      ctx.fillText(self.data.inputValue.substring(32), p_width * 375 / 750, p_height * 730 / 1334, p_width * 450 / 750)
    } else if (Math.floor(self.data.inputValue.length / 20) == 3) {
      ctx.fillText(self.data.inputValue.substring(0, 16), p_width * 375 / 750, p_height * 630 / 1334, p_width * 450 / 750)
      ctx.fillText(self.data.inputValue.substring(16, 32), p_width * 375 / 750, p_height * 680 / 1334, p_width * 450 / 750)
      ctx.fillText(self.data.inputValue.substring(32 , 48), p_width * 375 / 750, p_height * 730 / 1334, p_width * 450 / 750)
      ctx.fillText(self.data.inputValue.substring(48), p_width * 375 / 750, p_height * 780 / 1334, p_width * 450 / 750)
    } else {
      ctx.fillText(self.data.inputValue, p_width * 375 / 750, p_height * 630 / 1334, p_width * 450 / 750)
    }
    // ctx.draw();
    if (!self.data.noQrCode){
      ctx.drawImage('../fgrh/f-qrCode.png', p_width * 62 / 750, p_height * 1090 / 1334, p_width * 184 / 750, p_height * 214 / 1334);
    }
    ctx.beginPath()
    ctx.arc(p_width / 2, p_height * 343 / 1443, p_width * 60 / 750, 0, 2 * Math.PI)
    ctx.closePath()
    ctx.setLineWidth(4);
    ctx.setStrokeStyle('red')
    ctx.stroke()
    ctx.clip()
    ctx.drawImage(self.data.perImgUrl, p_width * 309 / 750, p_height * 272 / 1443, p_width * 132 / 750, p_height * 132 / 1334);
    ctx.restore()
    ctx.draw();
  },
  saveImg() {
    var self = this;
    // 生成图片
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: self.data.p_width,
      height: self.data.p_height,
      destWidth: self.data.p_width,
      destHeight: self.data.p_height,
      canvasId: 'textCav',
      success(res) {
        console.log(res.tempFilePath);
        self.setData({
          filePath: res.tempFilePath
        })
      }
    });
    // 保存到相册
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
              wx.saveImageToPhotosAlbum({
                filePath: self.data.filePath,
                success(res) {
                  console.log(res)
                  wx.showModal({
                    title: '保存图片成功',
                    content: '拜年卡已经保存到您的手机相册，您可以在相册查看！',
                    showCancel: false
                  });
                }
              })
            }
          })
        } else {
          wx.saveImageToPhotosAlbum({
            filePath: self.data.filePath,
            success(res) {
              console.log(res)
              wx.showModal({
                title: '保存图片成功',
                content: '拜年卡已经保存到您的手机相册，您可以在相册查看！',
                showCancel: false
              });
            }
          })
        }
      }
    })
  },
  cancelBack() {
    this.setData({
      getPoster: true,
    })
  },





  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var imgUrl = wx.getStorageSync("userInfo").avatarUrl;
    var self = this;
    self.setData({
      perImgUrl: imgUrl,
      cardId: decodeURIComponent(options.cardId),
      is_pay: app.globalData.is_pay
    });
    perImgUrl: imgUrl
    console.log(self.data.perImgUrl);
    var openId = wx.getStorageSync('openId');
    wx.request({
      url: 'https://bnk.xiutub.com/home/api/payinfo?openId=' + openId + '&tmpId=' + self.data.cardId,
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        if (res.data.res) { // 去掉二维码
          self.setData({
            noQrCode: true
          })
        }
      }
    })



    wx.downloadFile({
      url: 'https://bnk.xiutub.com/Uploads/temp/j-bg.png',
      success: function (res) {
        self.setData({
          'picurl': res.tempFilePath,
          'downLoadStatus' : true
        });
        console.log(res);
      }
    })

    wx.downloadFile({
      url: imgUrl, // 仅为示例，并非真实的资源
      success(res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        if (res.statusCode === 200) {
          console.log(res);
          self.setData({
            perImgUrl: res.tempFilePath
          });
        }
      }
    });
    try {
      const res = wx.getSystemInfoSync()
      console.log(res.model)
      console.log(res.pixelRatio)
      console.log(res.windowWidth)
      console.log(res.windowHeight)
      console.log(res.language)
      console.log(res.version)
      console.log(res.platform)
      this.setData({
        p_width: res.windowWidth,
        p_height: res.windowHeight
      })
    } catch (e) {
      // Do something when catch error
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
        title: '新年快乐，万事如意！和我一起来制作自己的拜年卡吧！',
      path: '/pages/index/index'
    }
  }
})